#!/usr/bin/python
# -*- coding: utf-8 -*-

from  reportlab.lib.styles import ParagraphStyle as PS
from  reportlab.platypus import PageBreak, Image, Table, TableStyle
from  reportlab.platypus.paragraph import Paragraph
from  reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from  reportlab.platypus.tableofcontents import TableOfContents
from  reportlab.platypus.frames import Frame
from  reportlab.lib.units import cm
from  reportlab.lib.enums import TA_JUSTIFY
from  reportlab.lib import colors

from  reportlab.pdfgen import canvas

from conf import varas

class report():
    
    story = []
    toc = TableOfContents()

class Estilo():

    centrado = PS(name = 'centrado',
        fontSize = 30,
        leading = 30,
        alignment = 1,
        spaceAfter = 20)

    titulo = PS(name = 'titulo',
        fontSize = 18,
        leading = 18,
        alignment = 1,
        spaceAfter = 20,
        spaceBefore = 180)

    subtitulo = PS(name = 'subtitulo',
        fontSize = 16,
        leading = 18,
        alignment = 1,
        spaceAfter = 180,
        spaceBefore = 1)

    left = PS(name = 'left',
        fontSize = 16,
        leading = 16,
        alignment = 0,
        spaceAfter = 20)

    h1 = PS(
        name = 'Heading1',
        fontSize = 14,
        leading = 16,
        spaceBefore = 150,
        spaceAfter = 60)


    h2 = PS(name = 'Heading2',
        fontSize = 12,
        leading = 14,
        spaceAfter = 10)

    corpo = PS( name = 'corpo',
        fontSize = 11,
        leading = 15,
        spaceAfter = 10,
        alignment = TA_JUSTIFY)

    Autor = PS( name = 'autor',
        fontSize = 12,
        leading = 18,
        alignment = 1)

    logo = PS( name = 'logo',
        fontSize = 16,
        leading = 20,
        alignment = 1)

    local = PS( name = 'local',
        fontSize = 16,
        leading = 20,
        alignment = 1,  
        spaceBefore = 100)

    logo2 = PS( name = 'logo',
        fontSize = 14,
        leading = 20,
        alignment = 1)
    

def Capa():

    # Create an instance of TableOfContents. Override the level styles (optional)
    # and add the object to the story


    report.toc.levelStyles = [
        PS(fontSize=13, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16),
        PS(fontSize=11, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),
        ]

    # Logotipos

    logo = "images/LOGO_IPB.png"
    ipbeja = Image(logo, 3.5*cm, 2.55*cm)
    ipbeja.hAlign='LEFT'
    logo = "images/LOGO_ESTIG.png"
    estig = Image(logo, 3.5*cm, 2.70*cm)
    estig.hAlign='RIGHT'
    tit = [Paragraph("INSTITUTO POLITÉCNICO DE BEJA", Estilo.logo),Paragraph("Escola Superior de Tecnologia e Gestão", Estilo.logo2)]
    data = [[ipbeja, tit, estig]]
    table = Table(data, colWidths=[4*cm, 10*cm, 4*cm])
    table.setStyle([("VALIGN", (0,0), (0,0), "TOP")])

    # Build story.

    report.story.append(table)
    report.story.append(Paragraph('          Mestrado de Engenharia em Segurança Informática', Estilo.logo2))
    report.story.append(Paragraph('<b>Relatório de PortScan</b>', Estilo.titulo))
    pass

def Toc():

    report.story.append(Paragraph('<b>Conteúdo</b>', Estilo.left))
    report.story.append(report.toc)
    report.story.append(PageBreak())
    pass

def Titulo(x):

    report.story.append(Paragraph(x, Estilo.subtitulo))
    pass

def Autor(autor):
    for x in autor:
        report.story.append(Paragraph(x, Estilo.Autor))
    pass

def CapaBottom(x):
    report.story.append(Paragraph('BEJA', Estilo.local))
    report.story.append(Paragraph(x, Estilo.logo2))
    report.story.append(PageBreak())
    pass

class MyDocTemplate(BaseDocTemplate):

    """
    Classe Principal de criação do documento PDF
    """
    def __init__(self, filename, **kw):
        self.allowSplitting = 0
        apply(BaseDocTemplate.__init__, (self, filename), kw)
        template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 17*cm, 26*cm, id='F1')])
        self.addPageTemplates(template)

    def afterFlowable(self, flowable):
        "Registers TOC entries."
        if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                self.notify('TOCEntry', (0, text, self.page))
            if style == 'Heading2':
                self.notify('TOCEntry', (1, text, self.page))


    
def CreatePdf():

    """
    Criação do ficheiro de saida em formato PDF
    """
    print "Criando o relatório"
    import datetime
    now = datetime.datetime.now()
    Capa()
    Titulo("{0}".format(varas.IP))
    Autor(["Luís Filipe Reis (12829)","Paulo Jorge Viegas (12834)"])
    mes=["","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]
    CapaBottom("{0} de {1} de {2}".format(int(now.strftime("%d")),mes[int(now.strftime("%m"))],now.strftime("%Y")))

    report.story.append(Paragraph("Tabela de PortScan", Estilo.h2))
    table = Table([["Host", "State", "Port", "Serviço","SO"]] + varas.Data,colWidths=[4*cm, 1.5*cm, 1.5*cm, 2*cm, 4*cm])
    table.setStyle(TableStyle([('LINEABOVE', (0,0), (-1,-1), 1, colors.black)]))
    table.setStyle(TableStyle([('FONT', (0,0), (-1,0), "Helvetica-Bold", 8),
            ("FONT", (0,1), (-1,-1), "Helvetica", 7)]))
    table.setStyle([("VALIGN", (0,0), (0,0), "TOP")])
    report.story.append(table)

    filename='PortScanReport{0}.pdf'.format(str(now.strftime("%Y%m%d%H%M")))
    doc = MyDocTemplate(filename)
    doc.multiBuild(report.story)
